package com.play.ballen.im.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.hjq.toast.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.manager.EaseSystemMsgManager;
import com.hyphenate.easeui.model.EaseEvent;
import com.hyphenate.easeui.modules.conversation.EaseConversationListFragment;
import com.hyphenate.easeui.modules.conversation.EaseConversationListLayout;
import com.hyphenate.easeui.modules.conversation.model.EaseConversationInfo;
import com.mw.plp.uim.DemoHelper;
import com.mw.plp.uim.common.constant.DemoConstant;
import com.mw.plp.uim.common.interfaceOrImplement.OnResourceParseCallback;
import com.mw.plp.uim.common.livedatas.LiveDataBus;
import com.mw.plp.uim.common.net.Resource;
import com.play.ballen.R;
import com.play.ballen.data.PImGroupStatus;
import com.play.ballen.im.PvtChatActivity;
import com.play.ballen.mall.ui.im.vm.ConversationListViewModel;
import com.play.ballen.mall.ui.im.vm.MessageViewModel;
import com.play.ballen.network.ApiRepository;
import com.play.ballen.network.BallenRxHelper;
import com.play.ballen.utils.UserInfoManager;
import com.yuven.appframework.network.RxSchedulerHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.CompositeDisposable;

public class PvtConversationFragment extends EaseConversationListFragment implements View.OnClickListener {


    private ConversationListViewModel mViewModel;

    private List<EaseConversationInfo> mineConversations = new ArrayList<>();

    public static PvtConversationFragment newInstance() {
        Bundle args = new Bundle();
        PvtConversationFragment fragment = new PvtConversationFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        //添加搜索会话布局
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_mian_conversation_pvt, null);
        llRoot.addView(view, 0);
        conversationListLayout.getListAdapter().setEmptyLayoutId(R.layout.layout_conversation_default_empty);
        initViewModel();
    }

    @Override
    public boolean onMenuItemClick(MenuItem item, int position) {
        EaseConversationInfo info = conversationListLayout.getItem(position);
        Object object = info.getInfo();

//        if(object instanceof EMConversation) {
//            switch (item.getItemId()) {
//                case R.id.action_con_make_top :
//                    conversationListLayout.makeConversationTop(position, info);
//                    return true;
//                case R.id.action_con_cancel_top :
//                    conversationListLayout.cancelConversationTop(position, info);
//                    return true;
//                case R.id.action_con_delete :
//                    showDeleteDialog(position, info);
//                    return true;
//            }
//        }
        return super.onMenuItemClick(item, position);
    }

    private void showDeleteDialog(int position, EaseConversationInfo info) {
        ToastUtils.show("删除");
//        new SimpleDialogFragment.Builder((BaseActivity) mContext)
//                .setTitle(R.string.delete_conversation)
//                .setOnConfirmClickListener(R.string.delete, new DemoDialogFragment.OnConfirmClickListener() {
//                    @Override
//                    public void onConfirmClick(View view) {
//                        conversationListLayout.deleteConversation(position, info);
//                        LiveDataBus.get().with(DemoConstant.CONVERSATION_DELETE).postValue(new EaseEvent(DemoConstant.CONVERSATION_DELETE, EaseEvent.TYPE.MESSAGE));
//                    }
//                })
//                .showCancelButton(true)
//                .show();
    }

    @Override
    public void initListener() {
        super.initListener();
    }

    @Override
    public void initData() {
        //需要两个条件，判断是否触发从服务器拉取会话列表的时机，一是第一次安装，二则本地数据库没有会话列表数据
        if (DemoHelper.getInstance().isFirstInstall()
                && EMClient.getInstance().chatManager().getAllConversations().isEmpty()) {
            mViewModel.fetchConversationsFromServer();
        } else {
            super.initData();
        }
    }

    private void initViewModel() {
        mViewModel = new ViewModelProvider(this).get(ConversationListViewModel.class);
        mViewModel.getDeleteObservable().observe(getViewLifecycleOwner(), response -> {
            parseResource(response, new OnResourceParseCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean data) {
                    LiveDataBus.get().with(DemoConstant.MESSAGE_CHANGE_CHANGE).postValue(new EaseEvent(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.TYPE.MESSAGE));
                    //mViewModel.loadConversationList();
                    conversationListLayout.loadDefaultData();
                }
            });
        });

        mViewModel.getReadObservable().observe(getViewLifecycleOwner(), response -> {
            parseResource(response, new OnResourceParseCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean data) {
                    LiveDataBus.get().with(DemoConstant.MESSAGE_CHANGE_CHANGE).postValue(new EaseEvent(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.TYPE.MESSAGE));
                    conversationListLayout.loadDefaultData();
                }
            });
        });

        mViewModel.getConversationInfoObservable().observe(getViewLifecycleOwner(), response -> {
            parseResource(response, new OnResourceParseCallback<List<EaseConversationInfo>>(true) {
                @Override
                public void onSuccess(@Nullable List<EaseConversationInfo> data) {
                    conversationListLayout.setData(data);
                }
            });
        });

        MessageViewModel messageViewModel = new ViewModelProvider(this).get(MessageViewModel.class);
        LiveDataBus messageChange = messageViewModel.getMessageChange();
        messageChange.with(DemoConstant.NOTIFY_CHANGE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.GROUP_CHANGE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CHAT_ROOM_CHANGE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CONVERSATION_DELETE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CONVERSATION_READ, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CONTACT_CHANGE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CONTACT_ADD, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.CONTACT_UPDATE, EaseEvent.class).observe(getViewLifecycleOwner(), this::loadList);
        messageChange.with(DemoConstant.MESSAGE_CALL_SAVE, Boolean.class).observe(getViewLifecycleOwner(), this::refreshList);
        messageChange.with(DemoConstant.MESSAGE_NOT_SEND, Boolean.class).observe(getViewLifecycleOwner(), this::refreshList);

        conversationListLayout.setConversationFilter(new EaseConversationListLayout.ConversationFilter() {
            @Override
            public void onConversationSuccess(List<EaseConversationInfo> data) {
                getGroupInfo(data);
            }
        });
        conversationListLayout.setItemBackGround(getResources().getDrawable(R.drawable.bg_conversation_item));
    }

    private void refreshList(Boolean event) {
        if (event == null) {
            return;
        }
        if (event) {
            conversationListLayout.loadDefaultData();
        }
    }

    private void loadList(EaseEvent change) {
        if (change == null) {
            return;
        }
        if (change.isMessageChange() || change.isNotifyChange()
                || change.isGroupLeave() || change.isChatRoomLeave()
                || change.isContactChange()
                || change.type == EaseEvent.TYPE.CHAT_ROOM || change.isGroupChange()) {
            conversationListLayout.loadDefaultData();
        }
    }

    /**
     * 解析Resource<T>
     *
     * @param response
     * @param callback
     * @param <T>
     */
    public <T> void parseResource(Resource<T> response, @NonNull OnResourceParseCallback<T> callback) {
//        if(mContext instanceof BaseActivity) {
//            ((BaseActivity) mContext).parseResource(response, callback);
//        }
    }

    /**
     * toast by string
     *
     * @param message
     */
    public void showToast(String message) {
        ToastUtils.show(message);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public void onItemClick(View view, int position) {
        super.onItemClick(view, position);
        Object item = conversationListLayout.getItem(position).getInfo();
        if (item instanceof EMConversation) {
            if (EaseSystemMsgManager.getInstance().isSystemConversation((EMConversation) item)) {
                // SystemMsgsActivity.actionStart(mContext);
            } else {
                PvtChatActivity.actionStart(mContext, ((EMConversation) item).conversationId());
            }
        }
    }

    @Override
    public void notifyItemChange(int position) {
        super.notifyItemChange(position);
        LiveDataBus.get().with(DemoConstant.MESSAGE_CHANGE_CHANGE).postValue(new EaseEvent(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.TYPE.MESSAGE));
    }

    @Override
    public void notifyAllChange() {
        super.notifyAllChange();
    }

    private void getGroupInfo(List<EaseConversationInfo> data) {
        dealWith(data, DemoHelper.getInstance().getEMClient().groupManager().getAllGroups());
//        DemoHelper.getInstance().getEMClient().groupManager().get(new ResultCallBack<List<EMGroup>>() {
//            @Override
//            public void onSuccess(List<EMGroup> value) {
//                dealWith(data,value);
//            }
//
//            @Override
//            public void onError(int error, String errorMsg) {
//                Log.e("QQQ","获取已加组失败"+error+errorMsg);
//                conversationListLayout.setFilterData(new ArrayList<>());
//            }
//        });
    }

    private void dealWith(List<EaseConversationInfo> data, List<EMGroup> groups) {
        List<EaseConversationInfo> newConversations = new ArrayList<>();

        for (EaseConversationInfo conversationInfo : data) {
            if (isPvt(conversationInfo, groups)) {
                newConversations.add(conversationInfo);
            }
        }
        mineConversations.clear();
        if (newConversations.size() > 0) {
            List<String> roomIds = new ArrayList<>();
            for (EaseConversationInfo conversationInfo : newConversations) {
                EMConversation conversation = (EMConversation) conversationInfo.getInfo();
                roomIds.add(conversation.conversationId());
            }
            mineConversations.addAll(newConversations);
            getGroupStatus(roomIds);
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    conversationListLayout.setFilterData(mineConversations);
                }
            });
        }
    }

    private boolean isPvt(EaseConversationInfo conversationInfo, List<EMGroup> groups) {
        if (conversationInfo.getInfo() instanceof EMConversation) {
            EMConversation conversation = (EMConversation) conversationInfo.getInfo();
            if (conversation.getType() != EMConversation.EMConversationType.GroupChat) {
                return false;
            }
            for (EMGroup group : groups) {
                if (group.getGroupId().equals(conversation.conversationId())) {
                    if (group.getGroupName().startsWith("jiyu")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
        return false;
    }

    public void getGroupStatus(List<String> roomIds) {
        new CompositeDisposable()
                .add(new ApiRepository()
                        .getPrivateGroupStatus(roomIds)
                        .onErrorResumeNext(new BallenRxHelper.HttpErrorHandleFunc())
                        .compose(BallenRxHelper.transformResponse())
                        .compose(RxSchedulerHelper.io_main())
                        .subscribe(s -> {
                            addGroupInfo((Map<String, List<PImGroupStatus>>) s);
                        }, err -> {
                            addGroupInfo(null);
                        }));
    }

    private void addGroupInfo(Map<String, List<PImGroupStatus>> res) {
        for (EaseConversationInfo info : mineConversations) {
            info.chatModel = 1;
            EMConversation conversation = (EMConversation) info.getInfo();
            PImGroupStatus status = getOther(res.get(conversation.conversationId()));
            if (status != null && status.anonymous) {
                info.prvName = status.user_nickname;
            } else {
                info.prvName = "*****";
            }
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                conversationListLayout.setFilterData(mineConversations);
            }
        });
    }

    private PImGroupStatus getOther(List<PImGroupStatus> statuses) {
        if (statuses!=null) {
            for (PImGroupStatus status : statuses) {
                if (UserInfoManager.INSTANCE.getUserInfo().id != status.user_id) {
                    return status;
                }
            }
        }
        return null;
    }
    private void sendStatus(){
//        EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
//            msg.setChatType(EMMessage.ChatType.GroupChat);
//            msg.setFrom(inviter);
//            msg.setTo(groupId);
//            msg.setMsgId(UUID.randomUUID().toString());
//            msg.setAttribute(DemoConstant.EM_NOTIFICATION_TYPE, true);
//            msg.addBody(new EMTextMessageBody(context.getString(R.string.demo_group_listener_onAutoAcceptInvitationFromGroup, groupName)));
//            msg.setStatus(EMMessage.Status.SUCCESS);
        // save invitation as messages
//            EMClient.getInstance().chatManager().saveMessage(msg);
    }


}
